package com.edu.springcloud.filter;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.annotation.Annotation;
import java.text.spi.DateFormatProvider;
import java.util.Date;
import java.util.List;

/**
 * @作者 five-five
 * @创建时间 2021/6/8
 */
@Component
@Slf4j
public class MyLogGateFilter implements GlobalFilter, Ordered {

    /**
     * 可以使用这个来做令牌拦截
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("********come in 我们的全局过滤器"+new Date());
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        String uname = queryParams.getFirst("uname");
        if (uname == null) {
            log.info("********好哥哥，你的uname为空");
            response.setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            //setComplete:指示消息处理已完成，允许执行任何清理或处理结束任务
            return response.setComplete();
        }
        //放行
        return chain.filter(exchange);
    }

    /**
     * 优先级，数字越小，有限度越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
